/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-09-17
 * Time: 15:20
 */
public class HashBucket {
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array;
    public int useSize;
    public double load_factor = 0.75;

    public HashBucket() {
        array = new Node[10];
    }

    //放元素
    public void put(int key, int val) {
        Node newNode = new Node(key,val);
        int a = key % array.length;

        //判断是否有相同的key
        Node cul = array[a];
        while(cul != null) {
            if(cul.key == key) {
                cul.val = val;
                return;
            }
            cul = cul.next;
        }
        //头插法
        newNode.next = array[a];
        array[a] = newNode;
        useSize++;

        //检查负载因子
        if((useSize * 1.0/array.length) > load_factor) {
            //扩容
            grow();
        }
    }

    private void grow() {
        Node[] newArray = new Node[2 * array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null) {
                int newIndex = cur.key % newArray.length;
                //头插法
                Node curNext = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curNext;
            }
        }
        this.array = newArray;
    }

    //获取元素
    public int get(int key) {
        int index = key % array.length;
        Node cul = array[index];
        while(cul != null) {
            if(cul.key == key) {
                return cul.val;
            }
            cul = cul.next;
        }
        return -1;
    }
}
